package com.gitee.ywj1352.common.connect;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.List;


/**
 * @author wenjie.yang on 2019/10/24.
 */
public class ConnectManager {

    private static final String BASE_PATH = "/ROOT";

    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

    public void addRootNode(CuratorFramework client) throws Exception {
        Stat stat = client.checkExists().forPath(BASE_PATH);
        if (stat == null) {
            client.create().withMode(CreateMode.PERSISTENT).forPath(BASE_PATH);
            System.out.println("创建成功");
        }
    }

    public void createNode(CuratorFramework client,String nodeName,String addr) throws Exception {
        String path = BASE_PATH + "/" + nodeName +"/" +nodeName+"_node";
        SessionConnectionListener sessionConnectionListener = new SessionConnectionListener(path, addr);
        client.getConnectionStateListenable().addListener(sessionConnectionListener);
        client.create()
                .creatingParentContainersIfNeeded()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .forPath(path,addr.getBytes());
    }


    public List<Object> getNodeList(CuratorFramework client,String nodeName) throws Exception {
        String path = BASE_PATH + "/" + nodeName;
        List<String> chilernList = client.getChildren().forPath(path);
        chilernList.forEach(c->{

        });
        return null;
    }

    public CuratorFramework createConnection() {
        return CuratorFrameworkFactory.builder()
                .connectString("localhost:2181")
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .build();
    }

    public static void main(String[] args) throws Exception {
        ConnectManager connectManager = new ConnectManager();
        CuratorFramework connection = connectManager.createConnection();
        connection.start();
        connectManager.createNode(connection,"/HiServer/HiServer_node","localhost:8090");
        connectManager.createNode(connection,"/ROOT/HiServer/HiServer_node","localhost:8091");
    }


}
